package com.vpen.account.demo.utils;

import com.google.common.collect.ImmutableMap;
import com.vpen.account.demo.config.SpringContext;
import com.vpen.account.demo.model.dto.AccountUserDetails;
import com.vpen.account.demo.model.enums.LoginType;
import com.vpen.account.demo.service.AccountLoginService;
import com.vpen.account.demo.service.impl.PhoneLoginServiceImpl;
import com.vpen.account.demo.service.impl.UsernameLoginServiceImpl;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Map;

/**
 * 用户登录工具类
 *
 * @author 韦鹏
 */
public class LoginUserUtils {

    private static final Map<LoginType, AccountLoginService> loginServiceMap = new ImmutableMap.Builder<LoginType, AccountLoginService>()
            .put(LoginType.PHONE, SpringContext.getBean(PhoneLoginServiceImpl.class))
            .put(LoginType.USERNAME, SpringContext.getBean(UsernameLoginServiceImpl.class))
            .build();

    private static final AccountUserDetails ACCOUNT_USER_DETAILS = new AccountUserDetails();

    /**
     * @return com.yst.account.login.model.dto.AccountUserDetails
     * @author 韦鹏
     * @desc 获取当前登录的用户，此线程安全
     * @date 2022/7/18 9:41
     **/
    public static AccountUserDetails getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                AccountUserDetails principal = (AccountUserDetails) authentication.getPrincipal();
                principal.setPassword(null);
                return principal;
            }
        }
        return ACCOUNT_USER_DETAILS;
    }


    /**
     * 获取用户id
     */
    public static Long getUserId() {
        return getLoginUser().getId();
    }


    /**
     * 获取登录处理的服务
     *
     * @param type 类型
     * @return com.vpen.account.demo.service.AccountLoginService
     * @author 韦鹏
     * @date 2022/8/16 15:12
     **/
    public static AccountLoginService getAccountLoginService(LoginType type) {
        return loginServiceMap.get(type);
    }
}
